package com.zxs.controller;

import com.zxs.Util.PaymentUtil;
import com.zxs.domain.model.NotifyModel;
import com.zxs.service.KuaiqianPaymentService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class ReceNotifyController {

    @Value("${pay.kq.merchant}")
    private String merchantAcctId;

    private Logger logger = LoggerFactory.getLogger(ReceNotifyController.class);

    @Resource
    private KuaiqianPaymentService kuaiqianPaymentService;

    /**
     * 处理快钱发送给商家的异步通知（商家来接收支付结果）
     * @return
     */
    @GetMapping("/rece/notify")
    @ResponseBody
    private String notyfy(NotifyModel notifyModel){

        try {
            //验证商户号，是否是该商户的订单
            String KQmerchantAcctId = notifyModel.getMerchantAcctId();
            if (!merchantAcctId.equals(KQmerchantAcctId)) {
                //商户号不匹配，验证失败
                logger.info("商户号{}---订单号{}--不是本商家的！！！", notifyModel.getMerchantAcctId(), notifyModel.getOrderId());
                throw new RuntimeException("商户号不是该商家的");
            }

            //1、验证签名
            boolean flag = notifyModel.checkSign();
            if (!flag) {
                //验证签名错误
                logger.info("商户号{}---订单号{}---验证签名错误{}", notifyModel.getMerchantAcctId(), notifyModel.getOrderId(), flag);
                throw new RuntimeException("验证签名失败");
            }

            //2、处理订单支付逻辑，更新订单状态
            String handleResult = kuaiqianPaymentService.handleNotify(notifyModel);
            logger.debug("商家号{}----订单号{}----处理结果{}", notifyModel.getMerchantAcctId(), notifyModel.getOrderId(), handleResult);



        } catch (Exception e) {
            e.printStackTrace();

        }

        //3、返回响应
        /*
         * <result>1</result><redirecturl>http://www.yoursite.com/show.asp</redirecturl>
         * 如果result标签里面的值为数字1时，快钱会认为商户已经接收到支付结果并成功处理，
         * 快钱会按照redirecturl标签里面提供的地址，跳转到新的页面，
         * 同时把支付信息参数再次带过来。用户可以在新的页面里面看到商户给出的页面提示信息。
         * */
        //处理完成
        return "<result>1</result><redirecturl>http://localhost:8060/shop/rece/show</redirecturl>";
    }


    @GetMapping("/rece/show")
    public String showResult(NotifyModel notifyModel, Model model) {
        String msg = "";
        String orderId = notifyModel.getOrderId();
        //支付结果  10 支付成功  11 支付失败
        String payResult = notifyModel.getPayResult();
        if ("10".equals(payResult)) {
            msg = "祝您购物愉快，支付成功！！！";
        } else {
            msg = "抱歉，支付失败，请重新支付";
        }

        model.addAttribute("msg", msg);
        model.addAttribute("orderId", orderId);

        return "showResult";
    }

}
